package com.example.springboottest.student.service.impl;

import com.example.springboottest.student.dao.StuJpaDao;
import com.example.springboottest.student.model.Student;
import com.example.springboottest.student.service.StuJpa2Service;
import com.example.springboottest.student.service.StuJpa3Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("stuJpaService3")
public class StuJpaService3Impl implements StuJpa3Service {
    @Autowired
    private StuJpaDao stuJpaDao;

    @Override
    public List<Student> doFindALl() {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        return stuJpaDao.findAll(sort);
    }

    @Override
    public void doDeleteById(String id) {

    }

    @Override
    public void doCreate(Student student) {

    }

    @Override
    public void doUpdate(Student student) {
        stuJpaDao.save(student);
    }

    @Override
    public void doUpdateLock(Student student) {
//        stuJpaDao.save(student);
        Student _student = doFindById(student.getId());
        _student.setAge(10 + student.getAge());
//        stuJpaDao.save(_student);
        stuJpaDao.flush();
        try {
//            if (StringUtils.equals(student.getId(), "1"))
            Thread.sleep(20 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Student _student2 = doFindById(student.getId());
        System.out.println("_student2 == _student:\t" + (_student2 == student));
//        _student2.setAge(888);
//        stuJpaDao.save(_student2);
        System.out.println("age:\t" + _student2.getAge());
    }

    @Override
    public void idoUpdate(Student student) {
        Student _student = doFindById("3");
        System.out.println(_student.getAge());
        System.out.println();
        _student.setAddress("3333333333");
    }

    @Override
    public Student doFindById(String id) {
        Student student = stuJpaDao.findById(id).orElse(null);
        return student;
    }

    @Override
    public Page<Student> doPage() {
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(1, 2, sort);
        return stuJpaDao.findAll(pageable);
    }

    @Override
    public String doLock() {
        return "stop";
    }
}